package com.example.nettyclient.view.recycleview;

import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.nettyclient.R;
import com.example.nettyclient.bean.MessageBean;
import com.google.android.material.button.MaterialButton;

import java.util.ArrayList;
import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    List<MessageBean> allMessages = new ArrayList<>();

    public void setAllMessages(List<MessageBean> allMessages) {
        this.allMessages = allMessages;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View view = layoutInflater.inflate(R.layout.cell_normal, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        MessageBean messageBean = allMessages.get(position);
        if(messageBean.getType() == 0){//发送的数据
            holder.rightMsg.setText(messageBean.getMsg());
            holder.leftLayout.setVisibility(View.INVISIBLE);
        }else{
            holder.leftMsg.setText(messageBean.getMsg());
            holder.rightLayout.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public int getItemCount() {
        return allMessages.size();
    }

    //static 防止内存泄漏
    static class MyViewHolder extends RecyclerView.ViewHolder{
        TextView leftMsg;
        TextView rightMsg;
        LinearLayout leftLayout;
        LinearLayout rightLayout;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            leftMsg = itemView.findViewById(R.id.left_msg);
            rightMsg = itemView.findViewById(R.id.right_msg);
            leftLayout = itemView.findViewById(R.id.left_layout);
            rightLayout = itemView.findViewById(R.id.right_Layout);
        }
    }
}
